package com.tengxing.e1.FactoryTest;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.maiarstar.e101.protocol.cerebellum.api.exception.ProtocolException;
import com.maiarstar.e101.protocol.cerebellum.api.model.HOTInfo;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolGetter;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolSetter;
import com.maiarstar.e101.protocol.cerebellum.sdk.CerebellumProtocolSdkManager;

public class TMP_Test_Activity extends AppCompatActivity {
    private static final String TAG = "TMP_Test_Activity";
    private CerebellumProtocolSdkManager cerebellumProtocolSdkManager;
    Button btn_TMP_Pass, btn_TMP_Fail,
            btn_TMP1, btn_TMP2, btn_TMP3, btn_TMP4,
            btn_HOT_On, btn_HOT_Off, btn_HOT_Get;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    String sn_str = null;
    double temp_val = 0, hum_val = 0;
    int hot_val = -1;
    private static Handler handler_refresh_status_task;
    private static Runnable run_refresh_status_task;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_tmp_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        initCerebellumManager();
        Factory_TMP_BTN();
        Refresh_Status_Task_Init();
    }


    private void initCerebellumManager() {
        CerebellumProtocolSdkManager sdkProtocolManager = new CerebellumProtocolSdkManager(this);
        CerebellumProtocolSdkManager.SdkParams sdkParams = CerebellumProtocolSdkManager.getDeafultSdkParams();
        try {
            sdkProtocolManager.init(sdkParams);
        } catch (ProtocolException e) {
            Log.w(TAG, e.getMessage());
        }
        this.cerebellumProtocolSdkManager = sdkProtocolManager;
    }
    private void Factory_TMP_BTN() {
        btn_TMP_Pass = findViewById(R.id.btn_TMP_Pass);
        btn_TMP_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("TMP", "通过");
                if (editor.commit()) {
                    Toast.makeText(TMP_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(TMP_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                } else {
                    Toast.makeText(TMP_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_TMP_Fail = findViewById(R.id.btn_TMP_Fail);
        btn_TMP_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("TMP", "未通过");
                if (editor.commit()) {
                    Toast.makeText(TMP_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(TMP_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                } else {
                    Toast.makeText(TMP_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_TMP1 = findViewById(R.id.btn_TMP1);
        btn_TMP1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Refresh_TMP_Status(1, btn_TMP1);
            }
        });

        btn_TMP2 = findViewById(R.id.btn_TMP2);
        btn_TMP2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Refresh_TMP_Status(2, btn_TMP2);
            }
        });

        btn_TMP3 = findViewById(R.id.btn_TMP3);
        btn_TMP3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Refresh_TMP_Status(3, btn_TMP3);
            }
        });

        btn_TMP4 = findViewById(R.id.btn_TMP4);
        btn_TMP4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Refresh_TMP_Status(4, btn_TMP4);
            }
        });

        btn_HOT_On = findViewById(R.id.btn_HOT_On);
        btn_HOT_On.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetHOT(1, 1)){
                    Toast.makeText(TMP_Test_Activity.this, "加热片开启，设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(TMP_Test_Activity.this, "加热片开启，设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_HOT_Off = findViewById(R.id.btn_HOT_Off);
        btn_HOT_Off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetHOT(1, 0)){
                    Toast.makeText(TMP_Test_Activity.this, "加热片关闭，设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(TMP_Test_Activity.this, "加热片关闭，设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_HOT_Get = findViewById(R.id.btn_HOT_Get);
        btn_HOT_Get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Refresh_HOT_Status(btn_HOT_Get);
            }
        });
    }

    private void Refresh_Status_Task_Init(){
        handler_refresh_status_task = new Handler(Looper.getMainLooper());//新建任务
        run_refresh_status_task = new Runnable() {
            @Override
            public void run() {
                handler_refresh_status_task.postDelayed(this, 5000);
                Refresh_TMP_Status(1, btn_TMP1);
                Refresh_TMP_Status(2, btn_TMP2);
                Refresh_TMP_Status(3, btn_TMP3);
                Refresh_TMP_Status(4, btn_TMP4);
                Refresh_HOT_Status(btn_HOT_Get);
                Log.d(TAG, "Refresh_Status_Cycle:in");
            }
        };
        handler_refresh_status_task.post(run_refresh_status_task);//启动任务
        //Log.d(TAG, "Refresh_Status_Cycle:out");
    }

    private void Refresh_TMP_Status(int num, Button btn){
        String sht40_str = "刷新温湿度"+num+"：状态未知";
        sn_str = null;
        temp_val = 0;
        hum_val = 0;
        if(GetTMP(num)){
            sht40_str = "刷新温湿度"+num+"："+temp_val+"℃  "+hum_val+"%  SN:"+sn_str;
            //Toast.makeText(TMP_Test_Activity.this, "刷新成功", Toast.LENGTH_SHORT).show();
        }else{
            sht40_str = "刷新温湿度"+num+"：获取失败";
            //Toast.makeText(TMP_Test_Activity.this, "刷新失败", Toast.LENGTH_SHORT).show();
        }
        btn.setText(sht40_str);
    }


    private boolean GetTMP(int num) throws ProtocolException {
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            temp_val = getter.getTMPInfo(num).getTemp();
            hum_val = getter.getHUMInfo(num).getHumidity();
            sn_str = getter.getSSNInfo(num).getSn();
            return true;
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }


    private boolean SetHOT(int num, int pwr) throws ProtocolException {
        try {
            HOTInfo hotInfo = new HOTInfo();
            hotInfo.setOrder(num);
            hotInfo.setPower(pwr);
            ICerebellumProtocolSetter setter = this.cerebellumProtocolSdkManager.getCerebellumProtocolSetter();
            return setter.setHOTInfo(hotInfo);
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }

    private boolean GetHOT(int num) throws ProtocolException {
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            hot_val = getter.getHOTInfo(num).getPower();
            return true;
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }

    private void Refresh_HOT_Status(Button btn){
        String hot_str = "刷新加热片状态：状态未知";
        hot_val = -1;
        if(!GetHOT(1)){
            Toast.makeText(TMP_Test_Activity.this, "刷新失败", Toast.LENGTH_SHORT).show();
        }

        if(hot_val == 1){
            hot_str = "刷新加热片状态：开启";
        } else if (hot_val == 0) {
            hot_str = "刷新加热片状态：关闭";
        }else{
            hot_str = "刷新加热片状态：刷新失败";
        }
        btn.setText(hot_str);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(TMP_Test_Activity.this, MainActivity.class);
        startActivity(intent);
        handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
        finish();
        Toast.makeText(TMP_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }
}